route.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { NextRequest, NextResponse } from "next/server";
  2. async function handle(
  3. req: NextRequest,
  4. { params }: { params: { path: string[] } },
  5. ) {
  6. if (req.method === "OPTIONS") {
  7. return NextResponse.json({ body: "OK" }, { status: 200 });
  8. }
  9. const [protocol, ...subpath] = params.path;
  10. const targetUrl = `${protocol}://${subpath.join("/")}`;
  11. const method = req.headers.get("method") ?? undefined;
  12. const shouldNotHaveBody = ["get", "head"].includes(
  13. method?.toLowerCase() ?? "",
  14. );
  15. const fetchOptions: RequestInit = {
  16. headers: {
  17. authorization: req.headers.get("authorization") ?? "",
  18. },
  19. body: shouldNotHaveBody ? null : req.body,
  20. method,
  21. // @ts-ignore
  22. duplex: "half",
  23. };
  24. const fetchResult = await fetch(targetUrl, fetchOptions);
  25. console.log("[Any Proxy]", targetUrl, {
  26. status: fetchResult.status,
  27. statusText: fetchResult.statusText,
  28. });
  29. return fetchResult;
  30. }
  31. export const POST = handle;
  32. export const GET = handle;
  33. export const OPTIONS = handle;
  34. export const runtime = "nodejs";